package com.siblings.loan.ui.steps.view

import android.annotation.SuppressLint
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.siblings.loan.R
import com.siblings.loan.app.Apps
import com.siblings.loan.databinding.ItemStepAccountBinding
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.steps.act.SibStepsAct
import com.siblings.loan.ui.steps.adapter.SibStepAccountAdapter
import com.siblings.loan.utils.dialog.BindCardAddDialog
import com.siblings.loan.utils.dialog.BindCardDeleteDialog
import com.siblings.loan.utils.dialog.BindCardOtherDialog
import com.siblings.loan.utils.dialog.BindCardSubmitDialog
import com.siblings.loan.utils.dialog.BindCardSubmitWarningDialog
import com.siblings.loan.utils.event.SibEventType
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/10 15:13
 * @Annotation：步骤账户样式
 */
class SibStepAccountView(private val stepAct: SibStepsAct) {
    var binding = ItemStepAccountBinding.inflate(stepAct.layoutInflater)

    @SuppressLint("StaticFieldLeak")
    private var accountAdapter: SibStepAccountAdapter? = null

    init {
        initSibContactViews()
        initSibContactListener()
    }

    /**
     * 联系人样式
     */
    fun includeSibStepAccountView(): View {
        return binding.root
    }

    /**
     * 初始化Views
     */
    private fun initSibContactViews(){
        //        binding.recyclerView.setHasFixedSize(true)
        binding.recyclerView.isNestedScrollingEnabled = false
        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(stepAct)
        layoutManager.orientation = RecyclerView.VERTICAL
        binding.recyclerView.layoutManager = layoutManager
        accountAdapter = SibStepAccountAdapter(binding.recyclerView)
        binding.recyclerView.adapter = accountAdapter!!
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        accountAdapter!!.setOnItemChildClickListener { _, childView, position ->
            val item = accountAdapter!!.getItem(position)
            when(childView.id){
                R.id.editLayout -> {//添加
                    showSibBinCardAddDialog()
                }
                R.id.deleteLayout -> {//删除
                    showSibDeleteDialog(item)
                }
            }
        }
    }

    /**
     * 初始化事件监听
     */
    private fun initSibContactListener(){
        //添加账户
        binding.addLayout.setOnClickListener {
            showSibBinCardAddDialog()
        }

        //提交
        binding.btnNext.setOnClickListener {
            if (!isSubmit()){
                stepAct.showSibTipsDialog("StepAccount Page")
                return@setOnClickListener
            }
            HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_STEP_ACCOUNT_CONFIRM_SUBMIT,"")
            checkSibSubmit()
        }
    }

    /**
     * 设置已绑定的账户列表数据
     */
    fun setSibAccountListData(accountList: ArrayList<JSONObject>){
        accountAdapter!!.data = accountList
    }

    /**
     * 添加绑卡dialog
     */
    private fun showSibBinCardAddDialog(){
        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER_ACCOUNT_ADD,"StepAccount Page")
        val bindCardDialog = BindCardAddDialog(stepAct,"StepAccount Page",object : BindCardAddDialog.IDialogCallback{
            override fun onClick(view: View?) {
            }
            override fun onSubmitParams(typeObj: JSONObject, phoneNumber: String) {
                stepAct.mvpPresenter.submitSibBindAccountAction(phoneNumber,typeObj.optString("value"))
            }
        })
        bindCardDialog.setCancelable(true)
        bindCardDialog.setCanceledOnTouchOutside(true)
        bindCardDialog.show()
    }

    /**
     * 提示绑定另一个渠道账户
     */
    fun showSibBingAccountOtherDialog(otherInfo: JSONObject) {
        val replaceDialog = BindCardOtherDialog(Apps.context,"StepAccount Page",object : BindCardOtherDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btnRight){//添加
                    stepAct.mvpPresenter.submitSibBindAccountAction(otherInfo.optString("walletMobile"),otherInfo.optString("value"), "YES")
                }
            }
        })
        replaceDialog.setCancelable(true)
        replaceDialog.setCanceledOnTouchOutside(false)
        replaceDialog.show()
        replaceDialog.setBindAccountInfo(otherInfo)
    }

    /**
     * 删除提示
     */
    private fun showSibDeleteDialog(item: JSONObject){
        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER_ACCOUNT_DELETE,item.optString("id"))
        val deleteDialog = BindCardDeleteDialog(stepAct,"StepAccount Page", object : BindCardDeleteDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btnRight){
                    stepAct.mvpPresenter.deleteSibAccountAction(item.optString("id"))
                }
            }
        })
        deleteDialog.setCancelable(true)
        deleteDialog.setCanceledOnTouchOutside(false)
        deleteDialog.show()
        deleteDialog.setBindAccountInfo(item)
    }

    /**
     * 只有一个账户警告提示
     */
    private fun showSubmitWarningDialog(){
        val warningDialog = BindCardSubmitWarningDialog(stepAct,"StepAccount Page",object : BindCardSubmitWarningDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.btnNoMore -> {//提交(不再有账户)
                        // TODO: 发送通知，更新主流程
                        stepAct.showSibSubmitSuccess()
                    }
                    R.id.btnAdd -> {//继续添加
                        showSibBinCardAddDialog()
                    }
                }
            }
        })
        warningDialog.setCancelable(true)
        warningDialog.setCanceledOnTouchOutside(false)
        warningDialog.show()
    }

    /**
     * 确认dialog
     */
    private fun showSibConfirmDialog(){
        val submitDialog = BindCardSubmitDialog(stepAct,object : BindCardSubmitDialog.IDialogCallback{
            override fun onClick(view: View?) {
                if (view!!.id == R.id.btnConfirm){
                    HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER_ACCOUNT_SUBMIT_TIPS_CONFIRM,"")
                    // TODO: 发送通知，更新主流程
                    stepAct.showSibSubmitSuccess()
                }
            }
        })
        submitDialog.show()
        submitDialog.setBindAccountList(accountAdapter!!.data)
    }

    /**
     * 提交按钮是否可点
     */
    private fun isSubmit(): Boolean{
        //提交按钮是否可点
        var submitIsEnabled = false
        for (i in 0..<accountAdapter!!.itemCount){
            //存在一个不是编辑状态的item，则可以提交
            if (!accountAdapter!!.getItem(i).optBoolean("isEdit",true)){
                submitIsEnabled = true
                break
            }
        }
        return submitIsEnabled
    }

    /**
     * 检查提交
     */
    private fun checkSibSubmit(){
        var count = 0
        accountAdapter!!.data.forEach {
            //不是编辑类型
            if (!it.optBoolean("isEdit",true)){
                count += 1
            }
        }
        //只有一个账户，需要提示
        if (count <= 1){
            showSubmitWarningDialog()
            return
        }
        //预览所有账户列表
        showSibConfirmDialog()
    }

    fun onDestroy(){
        if (accountAdapter != null){
            accountAdapter = null
        }
    }
}